<template>
	<section class="wrapper">
		<el-drawer v-model="state.drawer" size="40%" :close-on-click-modal="false" footer-class="drawer_footer">
			<template #header><span style="text-align: left;">选择云手机</span></template>
			<div>
				<div class="searchbox" style="text-align: left;">
					<el-autocomplete v-model="state.check_cloud_id" :fetch-suggestions="querySearch"
						popper-class="my-autocomplete" placeholder="请输入云机ID" @select="handleSelect"
						style="width: 240px;">
						<template #default="{ item }">
							<div>{{ item.instances.name }}</div>
						</template>
					</el-autocomplete>
					<el-button type="primary" color="#0079f2" :icon="Search" style="margin-left: 20px;">查询</el-button>
					<el-button :icon="Refresh" @click="state.check_cloud_id=''">重置</el-button>
				</div>
				<div class="table_div">
					<el-tabs v-model="state.activeName" class="demo-tabs">
						<el-tab-pane label="全部分组" name="first">
							<el-table :data="state.clouds_list" :header-cell-style="headerRowStyle"
								@selection-change="handleSelectionChange">
								<el-table-column type="selection" width="55" />
								<el-table-column label="云机ID">
									<template #default="scope">
										<span>{{scope.row.instances.name}}</span>
									</template>
								</el-table-column>
								<el-table-column property="instance_name" label="云机名称" />
							</el-table>
						</el-tab-pane>
					</el-tabs>
				</div>
			</div>
			<template #footer>
				<el-button type="primary" color="#0079f2" size="large" @click="Group_control">开始群控</el-button>
			</template>
		</el-drawer>
		<div class="left_phone">
			<div class="master-phone" v-if="state.master_phone.length>0">
				<div class="master-phone_content">
					<div class="phone_id_div">
						<p><span>{{state.master_phone[0].instance_name}}</span>({{state.master_phone[0].instances.name}})
						</p>
						<el-icon style="cursor: pointer;" size="20" color="#0079f2"
							@click="Copy_text(state.master_phone[0].instances.name)">
							<CopyDocument />
						</el-icon>
					</div>
					<div
						:id="`phone-display-${state.master_phone[0].instances.machine.ip}:${state.master_phone[0].instances.adb_port}`">
					</div>
				</div>
			</div>
			<div>

			</div>
		</div>
		<div class="main_phones">
			<div class="top_btns">
				<div>
					<el-checkbox v-model="store.state.is_sync" label="同步操作"
						@change="store.commit('change_is_sync', $event)" />
					<span>已选中 {{state.checked_phone_list.length}}</span>
					<el-button type="primary" color="#0079f2" @click="state.drawer=true">选择云手机</el-button>
					<el-button type="primary" color="#0079f2">批量输入</el-button>
					<el-button type="primary" color="#0079f2">批量上传</el-button>
					<el-button type="primary" color="#0079f2">视图模式</el-button>
				</div>
				<div>
					<span class="Batch_operations">批量操作</span>
					<el-popover popper-style="padding:0;" placement="bottom">
						<template #reference> <el-button><el-icon>
									<ArrowDown />
								</el-icon></el-button>
						</template>
						<div class="fun_options">
							<p>重启</p>
							<p>恢复出厂设置</p>
							<p>批量启动</p>
							<p>批量停止</p>
							<p>批量加载</p>
							<p>批量ADB</p>
						</div>
					</el-popover>
					<el-icon :size="20" style="margin-left: 20px;cursor: pointer;" @click.stop="closeOverlay">
						<Close />
					</el-icon>
				</div>
			</div>
			<div class="clouds_box" v-if="state.otherphone_list.length>0">
				<div v-for="(cloud_value,index) in state.otherphone_list" :key="cloud_value.id">
					<div class="clouds_id_div">
						<p><span>{{cloud_value.instance_name}}</span>({{cloud_value.instances.name}})</p>
						<el-icon style="cursor: pointer;" size="16" color="#0079f2"
							@click="Copy_text(cloud_value.instances.name)">
							<CopyDocument />
						</el-icon>
					</div>
					<div class="phone-display"
						:id="`phone-display-${cloud_value.instances.machine.ip}:${cloud_value.instances.adb_port}`"
						@click="change_master_phone(cloud_value,index)">
					</div>
				</div>
			</div>
			<div class="clouds_box" v-else>
				<div></div>
			</div>
			<div class="no_phone" v-if="state.master_phone.length==0 && state.otherphone_list==0">
				<div>
					<img src="@/assets/no_group.png" />
					<p>暂无云机</p>
				</div>
			</div>
		</div>
	</section>
</template>

<script setup>
	import {
		Ref,
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted,
		getCurrentInstance,
		watch
	} from 'vue';
	import {
		Close,
		Search,
		Refresh
	} from '@element-plus/icons-vue';
	import {
		Copy_text
	} from '@/utils/global_fun'
	import {
		StreamClientScrcpy
	} from '@/app/googDevice/client/StreamClientScrcpy';
	import request from '@/utils'
	import {
		ElMessage
	} from 'element-plus';
	import {
		useStore
	} from 'vuex';
	import {
		BroadcastService
	} from '@/app/interactionHandler/BroadcastService';
	const store = useStore();
	const appRouter = getCurrentInstance()?.appContext.config.globalProperties.$router
	const state = reactive({
		master_phone: [],
		drawer: true,
		activeName: 'first',
		check_cloud_id: null,
		clouds_list: [],
		otherphone_list: [],
		checked_phone_list: [],
		ws: null,
		StreamClientScrcpy_start: null,
		StreamClientScrcpy_start_list:[],
		playerRegistrations: [],
		connections: null,
	});
	class WebSocketManager {
		constructor() {
			this.connections = new Map(); // 使用实例属性替代state
		}
		// 建立单个连接（返回Promise<BasePlayer>）
		async connect(ip, adb_port, is_tool, ScreenW, ScreenH, zoomsize, is_master_cloud) {
			try {
				await initPlayers(ScreenW, ScreenH, zoomsize);
				const udid = `${ip}:${adb_port}`;
				const wsUrl = `wss://ws.jtcloud.icu:10443/?action=proxy-adb&remote=tcp:8886&udid=${udid}`;
				const parsedQuery = new URLSearchParams();
				// 参数设置
				parsedQuery.set("action", "stream");
				parsedQuery.set("player", "mse");
				parsedQuery.set("udid", udid);
				parsedQuery.set("hostname", "ws.jtcloud.icu");
				parsedQuery.set("ws", wsUrl);
				parsedQuery.set("port", '10443');
				parsedQuery.set("secure", "true");
				parsedQuery.set("clientId", adb_port);
				const rawPlayer = StreamClientScrcpy.start(
					parsedQuery,
					undefined,
					undefined,
					undefined,
					undefined,
					is_tool, //是否显示云手机配套的操作工具
					is_master_cloud
				);
				state.StreamClientScrcpy_start_list.push(rawPlayer)
			} catch (error) {
				console.error(`连接设备 ${ip} 失败:`, error);
				throw error;
			}
		}
		async connectMultiple(devices, is_tool, ScreenW, ScreenH, zoomsize, is_master_cloud) {
			const results = [];
			for (const item of devices) {
				try {
					const player = await this.connect(
						item.instances.machine.ip,
						item.instances.adb_port,
						is_tool, ScreenW, ScreenH, zoomsize, is_master_cloud
					);
					results.push({
						deviceId: item.instances.machine.ip,
						status: 'connected',
						player
					});
				} catch (error) {
					results.push({
						deviceId: item.instances.machine.ip,
						status: 'error',
						error: error.message
					});
				}
			}
			return results;
		}

		// 获取所有Player实例（同步方法）
		getAllPlayers() {
			return Array.from(this.players.values());
		}
	}
	const wsManager = ref(new WebSocketManager());
	async function Group_control() {
		if (state.checked_phone_list.length > 0) {
			const primaryDevice = state.checked_phone_list[0]
			state.master_phone.push(primaryDevice);
			const hasRemainingDevices = state.checked_phone_list.length > 1;
			if (hasRemainingDevices) {
				state.otherphone_list = state.checked_phone_list.slice(1)
				await wsManager.value.connectMultiple(state.otherphone_list, false, 1080, 1920, 0.2, false);
			}
			await wsManager.value.connectMultiple(state.master_phone, true, 1080, 1920, 0.4, true);
			state.drawer = false
		}
	}
	initdata() //渲染前执行请求
	function initdata() {
		get_clouds()
	}
	//获取当前用户的所有云手机
	function get_clouds() {
		const response = request.get('/containers/list')
		response.then((res) => {
			state.clouds_list = res.data.data
		}).catch(() => {})
	}
	const headerRowStyle = ({
		row,
		rowIndex
	}) => {
		return {
			backgroundColor: '#f0f3f5', // 背景色
			color: '#212224', // 文字颜色
		};
	};
	const querySearch = (queryString, callback) => {
		const results = queryString ? state.clouds_list.filter(item => item.instances.name.toLowerCase().includes(
			queryString
			.toLowerCase())) : state.clouds_list
		callback(results) // 返回筛选结果
	}

	function closeOverlay() {
		appRouter?.back()
	}
	//切换主设备
	const change_master_phone = async (cloud_value, index) => {
		BroadcastService.getInstance().unregisterClient()
		var other_phone = JSON.parse(JSON.stringify(state.master_phone[0]))
		state.master_phone[0] = cloud_value
		state.otherphone_list[index] = other_phone
		await wsManager.value.connectMultiple(state.master_phone, true, 1280, 1920, 0.4, true);
		await wsManager.value.connectMultiple(state.otherphone_list, false, 1280, 1920, 0.2, false);
	}
	const handleSelect = (item) => {
		state.check_cloud_id = item.instances.name
	}
	// 初始化播放器
	const initPlayers = async (ScreenW, ScreenH, zoomsize) => {
		const {
			MsePlayer
		} = await import('@/app/player/MsePlayer');
		StreamClientScrcpy.registerPlayer(MsePlayer);
		const {
			WebCodecsPlayer
		} = await import('@/app/player/WebCodecsPlayer');
		StreamClientScrcpy.registerPlayer(WebCodecsPlayer);
		MsePlayer.resize(ScreenW, ScreenH, zoomsize) //改变当前云手机屏幕的宽高和屏幕点击(x,y)缩放的大小
	};

	function handleSelectionChange(val) {
		state.checked_phone_list = val
	}
</script>

<style lang="less" scoped>
	.table_div {
		padding: 20px;
		margin-top: 20px;
		border: 1px solid #e5e8ee;
		border-radius: 5px;
	}

	.clouds_box {
		width: 100%;
		padding: 0 20px;
		height: calc(100vh - 50px);
		display: flex;
		justify-content: left;
		gap: 20px;
		align-items: center;
		transform: translateY(-25px);

		.phone-display {
			zoom: 0.2;
		}

		div {
			width: initial !important;
			height: initial !important;
		}
	}

	.drawer_footer {
		text-align: center;

		button {
			padding: 20px 70px;
		}
	}

	button {
		border-radius: 8px;
	}

	.wrapper {
		width: 100%;
		height: 100%;
		display: flex;

		.left_phone {
			width: 30%;
			height: 100%;
			background: url('@/assets/cloud_bgd.png');

			.master-phone {
				height: 100%;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.phone_id_div {
					width: 62%;
					zoom: 2.4 !important;
					padding: 10px 20px;
					background-color: #fff;
					display: flex;
					justify-content: space-between;
					align-items: center;

					span {
						font-weight: 900;
					}
				}
			}

			.master-phone_content {
				zoom: 0.4;

				>div {
					width: initial !important;
					height: initial !important;
				}
			}
		}

		.clouds_id_div {
			width: 40%;
			padding: 5px 10px;
			font-size: 10px;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;

			span {
				font-weight: 900;
			}
		}

		/deep/ .device-view {
			display: flex !important;
			flex-direction: row-reverse;
			flex-wrap: nowrap !important;
		}

		/deep/ .control-buttons-list {
			svg {
				width: 84px;
				height: 84px;
			}

			svg:hover {
				cursor: pointer;
			}
		}

		.main_phones {
			width: 70%;
			height: 100%;
			background-color: #f2f3f5;

			.top_btns {
				width: 100%;
				height: 50px;
				background-color: #fff;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20px;
				box-sizing: border-box;

				span {
					height: 32px;
					margin: 0 20px;
					font-size: 14px;
					text-align: center;
					line-height: 32px;
				}

				.Batch_operations {
					margin: 0;
					border: 1px solid #dcdfe6;
					color: #606266;
					border-radius: 10px 0 0 10px;
					padding: 0 10px;
					box-sizing: border-box;
				}

				.Batch_operations:hover {
					background-color: rgb(235.9, 245.3, 255);
					border-color: rgb(197.7, 225.9, 255);
					color: #409eff;
					cursor: pointer;
					outline: none;
				}

				.el-button.el-tooltip__trigger {
					border-left: none;
					padding: 8px 10px;
					border-radius: 0 10px 10px 0;
				}

				>div {
					display: flex;
					align-items: center;
				}
			}
		}

		.no_phone {
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #94979e;
		}
	}

	.fun_options {
		p {
			margin: 0;
			padding: 10px 0 10px 20px;
		}

		p:hover {
			background-color: rgb(235.9, 245.3, 255);
			color: #409eff;
			cursor: pointer;
		}
	}
</style>